package com.k8.common.factroy;

import com.k8.common.extension.Lifecycle;
import com.k8.common.ioc.BeanPostProcessor;
import com.k8.common.factroy.instance.AbstractBeanInstanceStrategyFactory;

public class BeanFactoryInstanceStrategyFactory extends AbstractBeanInstanceStrategyFactory {
    @Override
    protected <T> void doAfterPostProcessor(T instance, String name) {
    }

    @Override
    protected <T> T doPostProcessor(T instance, String name) {
        for (BeanPostProcessor beanPostProcessor : this.beanPostProcessors) {
            T t = beanPostProcessor.postProcessBeforeInitialization(instance, name);
            if (t == null)
                throw new RuntimeException("BeanPostProcessor return null, " + beanPostProcessor.getClass().getName());
            instance = t;
        }
        if (instance instanceof BeanInitialize beanInitialize) {
            beanInitialize.initialize();
        }
        if (instance instanceof Lifecycle lifecycle) {
            lifecycle.initialize();
        }
        for (BeanPostProcessor beanPostProcessor : this.beanPostProcessors) {
            T t = beanPostProcessor.postProcessAfterInitialization(instance, name);
            if (t == null)
                throw new RuntimeException("BeanPostProcessor return null, " + beanPostProcessor.getClass().getName());
            instance = t;
        }
        return instance;
    }
}
